package com.wwtech.epp.ui.activity.work;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.entity.TaskDetail;
import com.wwtech.epp.entity.TaskList;
import com.wwtech.epp.entity.eventbus.TaskChange;
import com.wwtech.epp.ui.activity.base.MyBaseFragment;
import com.wwtech.epp.ui.activity.work.component.DaggerTaskListComponent;
import com.wwtech.epp.ui.activity.work.contract.TaskListContract;
import com.wwtech.epp.ui.activity.work.module.TaskListModule;
import com.wwtech.epp.ui.activity.work.presenter.TaskListPresenter;
import com.wwtech.epp.ui.adapter.work.TaskListAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.work
 * @Description: $description
 * @date 2017/10/04 11:54:28
 */

public class TaskListFragment extends MyBaseFragment implements TaskListContract.View, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    @Inject
    TaskListPresenter mPresenter;
    @Inject
    TaskListAdapter taskListAdapter;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    private String mType;
    private int mNextPage;
    private static final int ONE_PAGE_SIZE = 5;
    private int total;
    private static final String ARG_TYPE = "arg_type";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task_list, null);
        ButterKnife.bind(this, view);
        Bundle mBundle = getArguments();
        refreshLayout.setOnRefreshListener(this);
        EventBus.getDefault().register(this);
        if (mBundle.getString(ARG_TYPE).equals("我发布的")) {
            taskListAdapter.categry = 0;
        } else {
            taskListAdapter.categry = 1;
        }
        taskListAdapter.setOnLoadMoreListener(this, recyclerView);
        taskListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                Intent intent = new Intent(getActivity(), TaskDetailActivity.class);
                intent.putExtra("dataBean", taskListAdapter.getData().get(i));
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(taskListAdapter);
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTaskStateChange(TaskChange taskChange) {
        for (TaskDetail data : taskListAdapter.getData()) {
            if (data.getJobId() == taskChange.taskId) {
                data.setJobState(taskChange.taskState);
                taskListAdapter.notifyDataSetChanged();
                return;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTaskCreate(String content) {
        if (content.equals("create")) {
            onRefresh();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mType = getArguments().getString(ARG_TYPE);
        }
    }

    @Override
    public void fetchData() {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                loadDataFromServer(true);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void loadDataFromServer(boolean showRefresh) {
        refreshLayout.setRefreshing(showRefresh);
        if (showRefresh) {
            mNextPage = 1;
        }
        mPresenter.getTaskListFromServer(mType, mNextPage, ONE_PAGE_SIZE);
    }

    public static TaskListFragment newInstance(String param) {
        TaskListFragment fragment = new TaskListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_TYPE, param);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onRefresh() {
        mNextPage = 1;
        loadDataFromServer(true);
    }

    @Override
    public void onLoadMoreRequested() {
        if (taskListAdapter.getData().size() < ONE_PAGE_SIZE || taskListAdapter.getData().size() >= total) {
            taskListAdapter.loadMoreEnd(true);
            return;
        }
        mNextPage++;
        mPresenter.getTaskListFromServer(mType, mNextPage, ONE_PAGE_SIZE);
    }


    @Override
    protected void setupFragmentComponent() {
        DaggerTaskListComponent
                .builder()
                .appComponent(((AppConfig) getActivity().getApplication()).getApplicationComponent())
                .taskListModule(new TaskListModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(TaskListContract.TaskListContractPresenter presenter) {
        mPresenter = (TaskListPresenter) presenter;
    }

    @Override
    protected void initDataFromLocal() {

    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    @Override
    public void setListData(TaskList taskList) {
        total = taskList.getData().getTotal();
        if (mNextPage == 1) {
            refreshLayout.setRefreshing(false);
            taskListAdapter.setNewData(taskList.getData().getList());
        } else {
            taskListAdapter.loadMoreComplete();
            taskListAdapter.addData(taskList.getData().getList());
        }
    }

}